package com.xt.partjobback.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xt.partjobback.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;


/**
 * 上传工具类
 * @author leotong
 */

public class UploadUtil {
    @Value("${cos.secretId}")
    private String secretId;
    @Value("${cos.secretKey}")
    private String secretKey;
    @Value("${cos.region}")
    private String regionName;
    /**
     * 上传文件
     * @param file 文件
     * @return 文件url
     */
    public static  String uploadImg(MultipartFile file) throws Exception {
        //返回的图片路径，oss根目录加上阿里云的ENDPOINT地址，File.separator =\
        String imgUrl = null;
        try {
            String imgFileName = "img/";
            OSS ossClient = new OSSClientBuilder().build(CommonConstant.OOSURL, CommonConstant.KEY, CommonConstant.SELECT);
            InputStream inputStream = file.getInputStream();
            //上传的文件名
            String originName = file.getOriginalFilename();
            //保存路径为文件夹+文件名
            String fileName =  imgFileName+originName;
            ossClient.putObject(CommonConstant.BUCKNAME,fileName, inputStream);
            ossClient.shutdown();
            //前面的内容，阿里云文档上都有
            //上传成功后，获取文件路径+文件名；
            imgUrl = "https://" + CommonConstant.BUCKNAME+"."+CommonConstant.OOSURL+ "/"  +fileName;
        } catch (Exception e) {
            throw new Exception("文件解析异常");
        }
        //将图片路径返回
        return imgUrl;
    }

}
